package xzl.edu.cn.book.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import xzl.edu.cn.book.dao.impl.BookDaoImpl;
import xzl.edu.cn.book.entity.Book;
import xzl.edu.cn.book.service.BookManager;

public class BookManagerlmpl implements BookManager {
	protected Logger logger = LogManager.getLogger(this.getClass().getName());
	List<Book> bookList;
	BookDaoImpl bookDao = new BookDaoImpl();

	@Override
	public void loadAdd(String data_file) {
		this.bookList = new ArrayList<Book>();
		InputStream input = BookManagerlmpl.class.getResourceAsStream(data_file);
		XSSFWorkbook wb = null;
		try {
			wb = new XSSFWorkbook(input);
		} catch (IOException e) {
			e.printStackTrace();
		}
		XSSFSheet sheet = wb.getSheetAt(1);
		for (int i = 1; i <= sheet.getLastRowNum(); i++) {
			Row row = sheet.getRow(i);
			Book s = new Book();
			/**
			 * Set the system unique Id for object
			 */
			s.setId(Long.valueOf(1000 + i));
			for (int j = 0; j < row.getLastCellNum(); j++) {
				Cell cell = row.getCell(j);
				if (cell != null) {
					cell.setCellType(CellType.STRING);
					String value = row.getCell(j).getStringCellValue().trim();
					if (j == 0)
						s.setName(value);
					if (j == 1)
						s.setPrice(value);
					if (j == 2)
						s.setSize(value);
				}
			}
			logger.info(" book_" + i + " is :" + s);
			this.bookList.add(s);
			this.bookDao.add(s); //添加到数据库 
		}
		logger.info("size of book list is :" + this.bookList.size());

	}

	@Override
	public Book findByNameBoo(String name) {
		return bookDao.findByName(name);
	}

	@Override
	public List<Book> queryAllBoo() {
		return bookDao.queryall();
	}

	@Override
	public void upDateBoo(Book pBook) {
		bookDao.upDate(pBook);

	}

	@Override
	public void deleteBoo(Book pbook) {
		bookDao.delete(pbook);
	}

}
